/**
 * 会员
 */
define(['jquery', 'base', 'msgTool'], function ($, base, msgTool) {
    //默认加载基础库
    base();

    /**
     * 浏览器检测
     * @returns {string}
     */
    function myBrowser() {
        //取得浏览器的userAgent字符串
        var userAgent = navigator.userAgent;
        //判断是否Opera浏览器
        var isOpera = userAgent.indexOf("Opera") > -1;
        if (isOpera) {
            return "Opera"
        }
        //判断是否Firefox浏览器
        if (userAgent.indexOf("Firefox") > -1) {
            return "FF";
        }

        if (userAgent.indexOf("Chrome") > -1) {
            return "Chrome";
        }

        //判断是否Safari浏览器
        if (userAgent.indexOf("Safari") > -1) {
            return "Safari";
        }

        //判断是否IE浏览器
        if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
            return "IE";
        }

        if (!!window.ActiveXObject || "ActiveXObject" in window) {
            return "IE";
        }
    }


    //执行
    return {
        register: function () {

            /**
             * 仿刷新：检测是否存在cookie
             */
            if ($.cookie("phoneCode")) {
                var count = $.cookie("phoneCode");
                var btn = $("#getCode");
                btn.text(count + '秒后可重新获取').attr('disabled', true).css('cursor', 'not-allowed');
                var resend = setInterval(function () {
                    count--;
                    if (count > 0) {
                        btn.text(count + '秒后可重新获取').attr('disabled', true).css('cursor', 'not-allowed');
                        $.cookie("phoneCode", count, {path: '/', expires: (1 / 86400) * count});
                    } else {
                        clearInterval(resend);
                        btn.text("获取验证码").removeClass('disabled').removeAttr('disabled style');
                    }
                }, 1000);
            }


            /**
             * 点击改变按钮状态，已经简略掉ajax发送短信验证的代码
             */
            $("#getCode").on('click', function () {
                var phoneNumber = $("#phone").val();
                if (phoneNumber === null || phoneNumber === '') {
                    var phone = $("#phone").parent();
                    phone.removeClass("has-success").addClass("has-error");
                    phone.find(".help-block").remove();
                    phone.append("<span class=\"help-block pull-left\"><i class=\"iconfont icon-error\"></i>请输入手机号码</span>");
                    return;
                }

                /**
                 * 执行发送
                 */
                $.ajax({
                    url: "/user/getSms",
                    method: "POST",
                    dataType: "json",
                    data: {mobile: phoneNumber},
                    success: function (data) {
                        if (data.success) {
                            msgTool.success(data.msg, "发送成功");
                        } else {
                            msgTool.error(data.msg, "发送失败");
                        }
                    },
                    error: function (jqXHR) {
                        msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                    }
                });


                /**
                 * 操作按钮
                 */
                var btn = $(this);
                var count = 60;
                var resend = setInterval(function () {
                    count--;
                    if (count > 0) {
                        btn.text(count + "秒后可重新获取");
                        $.cookie("phoneCode", count, {path: '/', expires: (1 / 86400) * count});
                    } else {
                        clearInterval(resend);
                        btn.text("获取验证码").removeAttr('disabled style');
                    }
                }, 1000);
                btn.attr('disabled', true).css('cursor', 'not-allowed');
            });

            //注册验证
            $("#registerForm").validate({
                rules: {
                    phone: {
                        required: true,
                        minlength: 11,
                        valiPhone: true,
                        remote: {
                            url: "/user/check",
                            type: "post",
                            data: {
                                param: function () {
                                    return $("#phone").val();
                                }
                            }
                        }
                    },
                    password: {
                        required: true,
                        rangelength: [8, 16],
                        valiPassword: true
                    },
                    confirmPassword: {
                        required: true,
                        rangelength: [8, 16],
                        valiPassword: true,
                        equalTo: "#password"
                    },
                    code: {
                        rangelength: [6, 6],
                        required: true,
                        // remote: {
                        //     url: "/common/sms/check",
                        //     type: "post",
                        //     data: {
                        //         code: function () {
                        //             return $("#code").val();
                        //         },
                        //         phone: function () {
                        //             return $("#phone").val();
                        //         },
                        //         status: function () {
                        //             return true;
                        //         }
                        //     }
                        // }
                    }

                },
                messages: {
                    phone: {
                        required: errorIcon + "请输入手机号",
                        minlength: $.validator.format(errorIcon + "手机号最少要输入{0}个字符。"),
                        remote: $.validator.format(errorIcon + "手机号“{0}”已经被注册。")
                    },
                    password: {
                        required: errorIcon + "请输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。")
                    },
                    confirmPassword: {
                        required: errorIcon + "请再次输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。"),
                        equalTo: errorIcon + "两次密码不相同。"
                    },
                    code: {
                        required: errorIcon + "请输入短信验证码",
                        rangelength: $.validator.format(errorIcon + "短信验证码为{0}数字。"),
                        remote: $.validator.format(errorIcon + "验证码错误")
                    }
                },
                success: function (key, value) {
                    $(value).parent().removeClass("has-error").addClass("has-success");
                }
            });

            //回车注册
            $(document).keyup(function (event) {
                if (event.keyCode === 13) {
                    $("#doSubmit").trigger("click");
                }
            });
            //点击注册
            $("#doSubmit").on('click', function () {
                var valid = $("#registerForm").valid();
                if (valid) {
                    $.ajax({
                        url: "/user/register",
                        type: 'POST',
                        data: $("#registerForm").serialize(),
                        dataType: "JSON",
                        cache: false,
                        async: false,
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            $("#doSubmit").text('注册中...');
                            $("#doSubmit").attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                window.location.href = data.model;
                            } else {
                                $("#messageCode").text(data.msg);
                            }
                        },
                        error: function () {
                            $("#messageCode").text("登录注册，请刷新页面后重试！");
                        },
                        complete: function () {
                            $("#doSubmit").text("注册");
                            $("#doSubmit").removeAttr('disabled');
                        }
                    });
                }
            });

        },
        login: function () {
        	 if(window.isAIO){
        	   /*一体机登陆界面*/
        	 $("#userLogin").html("<div id=\'raioLogin\'class=\'panel panel-default\'><div class=\'panel-heading\'><strong>统一身份认证平台账号登录</strong></div><div class=\'panel-body\'><h4 class=\'text-danger text-center\'id=\'messageCode\'></h4><div class=\'tabbable\'id=\'tabs\'><ul class=\'nav nav-tabs\'><li class=\'active\'><a href=\'#userLogin\'data-toggle=\'tab\'>个人登陆</a></li></ul><div class=\'tab-content mt15\'><div class=\'tab-pane active\'id=\'userLogin\'><div class=\'m-t-md\'><form class=\'form-horizontal\'method=\'post\'id=\'loginForm\'><input type=\'hidden\'name=\'rememberMe\'checked=\'checked\'><div class=\'form-group\'><label for=\'userName\'class=\'col-sm-2 control-label\'>账号</label><div class=\'col-sm-10\'><input type=\'text\'class=\'form-control input-lg\'id=\'username\'name=\'username\'placeholder=\'输入账号\'required=\'required\'></div></div><div class=\'form-group\'><label for=\'password\'class=\'col-sm-2 control-label\'>密码</label><div class=\'col-sm-10\'><input type=\'password\'class=\'form-control input-lg\'id=\'password\'name=\'password\'placeholder=\'输入密码\'required=\'required\'></div></div><hr/><div class=\'form-group\'><div class=\'col-sm-offset-2 col-sm-8\'><button type=\'button\'id=\'doSubmit\'class=\'btn btn-success btn-lg btn-block\'>&nbsp;登录&nbsp;</button></div></div></form></div></div></div></div></div><div class=\'panel-footer\'><div class=\'clearfix\'><div class=\'col-sm-6 text-left\'><a href=\'/user/resetPassword\'>找回密码</a></div><div class=\'col-sm-6 text-right\'><a href=\'/user/register\'>注册账号</a></div></div></div></div>");
             }else{
        	   /*  pc登陆界面*/
             $("#userLogin").html("<div id=\'webLogin\'class=\'panel panel-primary\'><div class=\'panel-body\'><h1 class=\'text text-danger text-center\'>用户登陆</h1><hr></hr><div class=\'col-xs-12 col-sm-12 col-md-12\'><div class=\'col-xs-12 col-sm-6 col-md-6 sudoku\'><a class=\'thumbnail color-1\'href=\'/user/personLogin\'style=\'text-decoration: none;\'><img src=\'/static/images/personLogin.png\'alt=\'个人用户登陆\'><div class=\'text  text-center\'>个人用户登陆</div></a></div><div class=\'col-xs-12 col-sm-6 col-md-6 sudoku\'><a class=\'thumbnail color-2\'href=\'/user/legalLogin\'style=\'text-decoration: none;\'><img src=\'/static/images/legalLogin.png\'alt=\'法人用户登陆\'><div class=\'text text-success text-center\'>法人用户登陆</div></a></div></div></div></div></div>");                 
            }

            //登录
            $("#loginForm").validate({
                rules: {
                    userName: {
                        required: true,
                        minlength: 2,
                        vailNamePhoneEmail: true
                    },
                    password: {
                        required: true,
                        rangelength: [6, 18],
                        valiPassword: true
                    }
                },
                messages: {
                    userName: {
                        required: errorIcon + "请输入账号",
                        minlength: $.validator.format(errorIcon + "账号最少要输入{0}个字符。")
                    },
                    password: {
                        required: errorIcon + "请输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。")
                    }
                }
            });
            //点击登录
            $("#doSubmit").on('click', function () {
                var valid = $("#loginForm").valid();
                if (valid) {
                    $.ajax({
                        url: "/user/login",
                        type: 'POST',
                        data: $("#loginForm").serialize(),
                        dataType: "JSON",
                        // cache: false,
                        // async: false,
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            $("#doSubmit").text('登录中...');
                            $("#doSubmit").attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                window.location.href = data.model;
                            } else {
                                $("#messageCode").text(data.msg);
                            }
                        },
                        error: function () {
                            $("#messageCode").text("登录失败，请稍后重试！");
                        },
                        complete: function () {
                            $("#doSubmit").text("登录");
                            $("#doSubmit").removeAttr('disabled');
                        }
                    });
                }
            });

        },
        resetPassword: function () {
            /**
             * 仿刷新：检测是否存在cookie
             */
            if ($.cookie("resetPassphoneCode")) {
                var count = $.cookie("resetPassphoneCode");
                var btn = $("#getCode");
                btn.text(count + '秒后可重新获取').attr('disabled', true).css('cursor', 'not-allowed');
                var resend = setInterval(function () {
                    count--;
                    if (count > 0) {
                        btn.text(count + '秒后可重新获取').attr('disabled', true).css('cursor', 'not-allowed');
                        $.cookie("resetPassphoneCode", count, {path: '/', expires: (1 / 86400) * count});
                    } else {
                        clearInterval(resend);
                        btn.text("获取验证码").removeClass('disabled').removeAttr('disabled style');
                    }
                }, 1000);
            }


            /**
             * 点击改变按钮状态，已经简略掉ajax发送短信验证的代码
             */
            $("#getCode").on('click', function () {
                var phoneNumber = $("#phone").val();
                if (phoneNumber === null || phoneNumber === '') {
                    var phone = $("#phone").parent();
                    phone.removeClass("has-success").addClass("has-error");
                    phone.find(".help-block").remove();
                    phone.append("<span class=\"help-block pull-left\"><i class=\"iconfont icon-error\"></i>请输入手机号码</span>");
                    return;
                }

                /**
                 * 执行发送
                 */
                $.ajax({
                    url: "/user/sendForgetMobile",
                    method: "POST",
                    dataType: "json",
                    data: {mobile: phoneNumber},
                    success: function (data) {
                        if (data.success) {
                            msgTool.success(data.msg, "发送成功");
                        } else {
                            msgTool.error(data.msg, "发送失败");
                        }
                    },
                    error: function (jqXHR) {
                        msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                    }
                });


                /**
                 * 操作按钮
                 */
                var btn = $(this);
                var count = 60;
                var resend = setInterval(function () {
                    count--;
                    if (count > 0) {
                        btn.text(count + "秒后可重新获取");
                        $.cookie("resetPassphoneCode", count, {path: '/', expires: (1 / 86400) * count});
                    } else {
                        clearInterval(resend);
                        btn.text("获取验证码").removeAttr('disabled style');
                    }
                }, 1000);
                btn.attr('disabled', true).css('cursor', 'not-allowed');
            });


            //找回密码
            $("#resetPasswordForm").validate({
                rules: {
                    phone: {
                        required: true,
                        minlength: 11,
                        valiPhone: true
                    },
                    password: {
                        required: true,
                        rangelength: [6, 18],
                        valiPassword: true
                    },
                    confirmPassword: {
                        required: true,
                        rangelength: [6, 18],
                        valiPassword: true,
                        equalTo: "#password"
                    },
                    code: {
                        rangelength: [6, 6],
                        required: true
                    }

                },
                messages: {
                    phone: {
                        required: errorIcon + "请输入手机号",
                        minlength: $.validator.format(errorIcon + "手机号最少要输入{0}个字符。"),
                        remote: $.validator.format(errorIcon + "手机号“{0}”已经被注册。")
                    },
                    password: {
                        required: errorIcon + "请输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。")
                    },
                    confirmPassword: {
                        required: errorIcon + "请再次输入密码",
                        rangelength: $.validator.format(errorIcon + "密码最少要输入{0}个字符。"),
                        equalTo: errorIcon + "两次密码不相同。"
                    },
                    code: {
                        required: errorIcon + "请输入短信验证码",
                        rangelength: $.validator.format(errorIcon + "短信验证码为{0}数字。")
                    }
                }
            });

            //点击提交
            $("#doSubmit").on('click', function () {
                var valid = $("#resetPasswordForm").valid();
                if (valid) {
                    $.ajax({
                        url: "/user/resetPassword",
                        type: 'POST',
                        data: $("#resetPasswordForm").serialize(),
                        dataType: "JSON",
                        cache: false,
                        async: false,
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            $("#doSubmit").text('提交中...');
                            $("#doSubmit").attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                $("#messageCode").text("密码重置成功，请重新登录！");
                                $("#resetPasswordForm")[0].reset();
                            } else {
                                $("#messageCode").text(data.msg);
                            }
                        },
                        error: function () {
                            $("#messageCode").text("重置密码失败，请稍后重试！");
                        },
                        complete: function () {
                            $("#doSubmit").text("提交");
                            $("#doSubmit").removeAttr('disabled');
                        }
                    });
                }
            });
        }
    }
});


